/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-2-20
 * 
**/
package com.julewa.loading;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.julewa.Authority;
import com.julewa.ThreadValue;
import com.julewa.db.Transaction;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("serial")
public final class StrutsInterceptor extends AbstractInterceptor{
	private @Autowired ClientImpl client;
	private @Autowired Transaction trans = null;
	private Authority auth = null;
	private static BeforeResultListener brl = new BeforeResultListener();
	//private @Autowired ContentType contentType;
	//private static Map<Class<?>, Method> classes = new HashMap<Class<?>, Method>();
	private static class LocalThreadValue extends ThreadValue<String>{
		public static void clean(){
			for(ThreadValue<?> t:THREADS)t.initialize();
		}
	};
	//private String encoding = null;
	
	public StrutsInterceptor(){
		//encoding = SystemUtils.getProperty("system.encoding", "UTF-8");
	};
	
	public void init(){
		super.init();
		auth = SpringLoader.getInstance(Authority.class);
	}
	
	@Override
    public String intercept(ActionInvocation ai) throws Exception{
		//
		LocalThreadValue.clean();
    	//
		HttpServletRequest req = ServletActionContext.getRequest();
		client.req .set(req);
		client.resp.set(ServletActionContext.getResponse());
		//
		if(auth != null){
			ActionProxy ap = ai.getProxy();
			String r = auth.getUnauthorizedResult(
				(ap.getNamespace() == null)?"/":ap.getNamespace(),
				ap.getActionName(),
				ai.getAction().getClass(),
				(ap.getMethod()==null)?"execute":ap.getMethod()
			);
			if(r != null)return r;
		}
		//
		brl.client = this.client;
		ai.addPreResultListener(brl);
		//
		RESTActionMapping.initRest(ai, req);
		//
		//response type
		/*
		String typ = client.getResponseType();
		if(typ != null)typ = contentType.get(typ);
		if(typ == null)typ = "text/html";
		resp.setContentType(typ);
		if(typ.startsWith("text/")){
			resp.setContentType(typ + ";charset=" + encoding);
		}else{
			resp.setContentType(typ);
		}
		*/
		try{
			return ai.invoke();
		}finally{
			if(trans.inProgress()){
				trans.stop();
			}
		}
    }
}
